import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025/5/28
 * Time: 22:09
 */

public class Solution {
    private static int i = 0;
    public static TreeNode createTree(int[] nums) {
        int cur = nums[i];
        TreeNode root = null;
        if (cur != -1) {
            root = new TreeNode(cur);
            i++;
            root.left = createTree(nums);
            root.right = createTree(nums);
        }else {
            i++;
        }
        return root;
    }
    public static List<Integer> rightSideView(TreeNode root) {
        List<List<TreeNode>> lists = levelOrderAdvanced(root);
        List<Integer> res = new ArrayList<>();
        for (List<TreeNode> l : lists) {
            res.add(l.get(l.size() - 1).val);
        }
        return res;
    }
    public static List<List<TreeNode>> levelOrderAdvanced(TreeNode root){
        List<List<TreeNode>> ret = new ArrayList<>();
        if (root == null){
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();
            //保存当前层数的节点
            List<TreeNode> curList = new ArrayList<>();
            while (size != 0){
                TreeNode curNode = queue.poll();
                curList.add(curNode);
                if (curNode != null && curNode.left != null){
                    queue.add(curNode.left);
                }
                if (curNode != null && curNode.right != null){
                    queue.add(curNode.right);
                }
                size--;
            }
            ret.add(curList);
        }
        return ret;
    }
    public static void main(String[] args) {
        TreeNode root = createTree(new int[]{1, 2, -1, 5, -1, -1, 3, -1, 4, -1, -1});
        List<Integer> list = rightSideView(root);
        for (Integer i : list) {
            System.out.print(i + " ");
        }
    }
}